import json

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.auth.credentials import AccessKeyCredential
from aliyunsdkcore.auth.credentials import StsTokenCredential
from aliyunsdkiot.request.v20180120.QueryDeviceDetailRequest import QueryDeviceDetailRequest
from aliyunsdkiot.request.v20180120.RegisterDeviceRequest import RegisterDeviceRequest
from aliyunsdkiot.request.v20180120.RRpcRequest import RRpcRequest

class AliMqttApi(object):
    def __init__(self, AccessKeyID,AccessKeySecret,regionId):
        self.AccessKeyID = AccessKeyID
        self.AccessKeySecret =AccessKeySecret
        self.regionId=regionId
        credentials = AccessKeyCredential(self.AccessKeyID, self.AccessKeySecret)
        # use STS Token
        # credentials = StsTokenCredential('<your-access-key-id>', '<your-access-key-secret>', '<your-sts-token>')
        self.client = AcsClient(region_id=self.regionId, credential=credentials)

    def QueryDeviceDetail(self,productKey, deviceName):
        request = RegisterDeviceRequest()
        request.set_accept_format('json')
        request.set_ProductKey(productKey)
        request.set_DeviceName(deviceName)
        response = self.client.do_action_with_exception(request)
        res=json.loads(str(response, encoding='utf-8'))
        return res

    def RegisterDevice(self,productKey, deviceName,nickName):

        request = RegisterDeviceRequest()
        request.set_accept_format('json')

        request.set_ProductKey(productKey)
        request.set_DeviceName(deviceName)
        request.set_Nickname(nickName)

        response = self.client.do_action_with_exception(request)
        res=json.loads(str(response, encoding='utf-8'))
        return res

    def RRPC(self,productKey, deviceName,topic,content):

        request = RRpcRequest()
        request.set_accept_format('json')

        request.set_ProductKey(productKey)
        request.set_DeviceName(deviceName)
        request.set_Timeout(8000)
        request.set_Topic(topic)
        request.set_content(content);

        response = self.client.do_action_with_exception(request)
        res=json.loads(str(response, encoding='utf-8'))
        return res